import axios from 'axios'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // console.log('aqie', store)
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['blade-auth'] = `bearer ${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
    200 OK：请求成功，并且服务器返回了请求的资源。
    301 Moved Permanently：请求的资源已被永久移动到新位置。
    400 Bad Request：服务器无法理解请求，通常是因为请求参数有误或格式不正确。
    401 Unauthorized：请求需要用户身份验证。
    403 Forbidden：服务器拒绝请求，一般是因为缺少访问权限。
    404 Not Found：请求的资源不存在。
    500 Internal Server Error：服务器内部错误，无法完成请求。
   */
  response => {
    // Notification.error({ title: 'aaaa' })
    // 这是后端返回数据

    // console.log('response', response)
    const res = response.data
    // console.log('response', response, response.status, res)
    // 后端返回状态码
    if (res.code !== 200) {

      if (res.code === 401 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      console.log("aqie error", res.msg)
      Notification.error({ title: res.msg })
      return Promise.reject('error')
    } else {
      return res
    }
  },
  error => {
    console.log('err', error.response) // 获取 HTTP 响应对象
    Notification.error({ title: error.response.data.msg })
    return Promise.reject(error)
  }
)

export default service
